package com.own.business.log.login.persistence.business.service.impl;

import com.own.business.log.login.persistence.business.service.LogLoginService;
import com.own.business.log.login.persistence.entity.bo.LogLoginBo;
import com.own.business.log.login.persistence.entity.map.LogLoginMapVo;
import com.own.business.log.login.persistence.entity.po.LogLogin;
import com.own.business.log.login.persistence.entity.query.LogLoginQuery;
import com.own.business.log.login.persistence.entity.vo.LogLoginVo;
import com.own.business.log.login.persistence.mapper.LogLoginMapper;
import com.own.component.common.base.service.impl.AbstractBaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * LogLoginServiceImpl
 *
 * @author chenxueli
 * @date 2023-08-07 22:25:01
 */
@Slf4j
@Service
public class LogLoginServiceImpl extends AbstractBaseService<
        LogLogin,
        LogLoginBo,
        LogLoginVo,
        LogLoginMapVo,
        LogLoginQuery,
        LogLoginMapper
        > implements LogLoginService {

    @Resource
    private LogLoginMapper logLoginMapper;

    /**
     * 根据用户id查询最新的登录日志信息
     *
     * @param userId 用户id
     * @return 最新的登录日志信息
     */
    @Override
    public LogLogin getLastLoginTimeByUserId(Long userId) {
        var wrapper = lambdaQueryWrapper()
                .eq(LogLogin::getFkUserId, userId)
                .eq(LogLogin::getStatus, 1)
                .orderByDesc(LogLogin::getGmtCreate);
        return getOneByWrapper(wrapper);
    }

    /**
     * 获取最近的一次登录日志信息
     *
     * @param account 账号信息
     * @param type    登录方式
     * @param status  登录的状态信息
     * @return 最新的登录日志信息
     */
    @Override
    public LogLogin getLastLoginTimeByAccountAndType(String account, String type, Integer status) {
        var wrapper = lambdaQueryWrapper()
                .eq(LogLogin::getLoginAccount, account)
                .eq(LogLogin::getLoginType, type)
                .eq(status != null, LogLogin::getStatus, status)
                .orderByDesc(LogLogin::getGmtCreate);
        return getOneByWrapper(wrapper);
    }

    /**
     * 根据时间查询当前登录失败的次数
     *
     * @param account   账号信息
     * @param type      登录方式
     * @param startTime 开始时间（不包含）
     * @param endTime   截止时间（不包含）
     * @return 登录的次数
     */
    @Override
    public long countByTimeAndAccountAndType(String account, String type, LocalDateTime startTime, LocalDateTime endTime) {
        var wrapper = lambdaQueryWrapper()
                .eq(LogLogin::getLoginAccount, account)
                .eq(LogLogin::getLoginType, type)
                .gt(startTime != null, LogLogin::getGmtCreate, startTime)
                .lt(endTime != null, LogLogin::getGmtCreate, endTime);
        return countByWrapper(wrapper);
    }

}
